package com.gxd.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        Properties properties = new Properties();
        try {
            InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(is);
            is.close();
            dataSource=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException("加载驱动失败");
        }
    }


    public static DataSource getDataSource(){
        return dataSource;
    }


    public static Connection getConnection() {
        Connection connection = threadLocal.get();
        try {
            if (connection == null) {
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            System.out.println("获取连接失败" + e.getMessage());
        }
        return null;
    }
    public static void begin() throws SQLException {

        Connection connection = getConnection();
        if (connection != null) {
            connection.setAutoCommit(false);
        }

    }

    public static void commit() throws SQLException {

        Connection connection = getConnection();
        if (connection != null) {
            connection.commit();
        }

    }

    public static void rollback() throws SQLException {

        Connection connection = getConnection();
        if (connection != null) {
            connection.rollback();
        }

    }

    public static void close() throws SQLException {

        Connection connection = getConnection();
        if (connection != null) {
            connection.close();
            threadLocal.remove();
        }

    }


}
